package com.adams.log.task;

import java.util.Timer;
import java.util.TimerTask;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.adams.access.db.bean.OptLog;
import com.adams.utils.AppContext;

public class OptLogTask extends TimerTask
{
	private static final int period = 60 * 1000;

	public static volatile boolean isStart;

	private static final String INSERT_SQL = "INSERT INTO t_opt_log(operator,operateEvent,operateTime,operateFrom,operateContent,version) VALUES";

	public static void start()
	{
		if (!isStart)
			synchronized (OptLogTask.class)
			{
				if (!isStart)
				{
					Timer timer = new Timer(true);
					timer.schedule(new OptLogTask(), 0, period);
					isStart = true;
				}
			}
	}

	public void run()
	{
		OptLog log = OptLogQueue.getLog();
		if (log != null)
		{
			SessionFactory sessionFactory = (SessionFactory) AppContext
					.getBean("sessionFactory");
			Session session = sessionFactory.openSession();

			StringBuilder values = new StringBuilder();
			appendSQL(values, log);

			while ((log = OptLogQueue.getLog()) != null)
			{
				appendSQL(values, log);
			}
			session.createSQLQuery(INSERT_SQL + values.toString())
					.executeUpdate();
			session.close();
		}
	}

	private void appendSQL(StringBuilder buffer, OptLog log)
	{
		if (buffer.length() > 0)
		{
			buffer.append(",");
		}
		buffer.append("('" + log.getOperator() + "',");
		buffer.append("'" + log.getOperateEvent() + "',");
		buffer.append("'" + log.getOperateTime() + "',");
		buffer.append("'" + log.getOperateFrom() + "',");
		buffer.append("'" + log.getOperateContent() + "',");
		buffer.append("'" + log.getVersion() + "')");
	}
}
